package com.zx.config;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义异常页面
 *
 * @author jack.wu
 * @version 1.0
 * @date 2020-03-09
 */
@Component
public class ExceptionHandlerPage implements UrlBlockHandler {

    /**
     * FlowException 限流异常
     * DegradeException 降级异常
     * ParamFlowException 参数限流异常
     * AuthorityException 授权异常
     * SystemBlockException 系统负载异常
     * @param request request
     * @param response response
     * @param e sentinel异常
     * @throws IOException
     */
    @Override
    public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException e) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        ResponseData responseData = getResponseDataByE(e);
        response.getWriter().write(JSON.toJSONString(responseData));
    }

    /**
     * 部分异常
     * @param e
     * @return
     */
    private ResponseData getResponseDataByE(BlockException e){
        ResponseData responseData = null;
        if (e instanceof FlowException){
            responseData = new ResponseData(-1,"限流异常");
        }else if (e instanceof DegradeException){
            responseData = new ResponseData(-2,"降级异常");
        }
        return responseData;
    }

}

@Data
@AllArgsConstructor
@NoArgsConstructor
class ResponseData{
    private int code;
    private String message;
}